package struts.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import struts.util.XmlBean;








public class strutsXml {
      public static Map<String,XmlBean>    read(String xmlPath) throws Exception{
		Map<String,XmlBean>  map=new HashMap<String,XmlBean>();
		XmlBean xmlBean=new XmlBean();
    	  SAXBuilder saxBuilder=new SAXBuilder();
    	  Document doc = saxBuilder.build(xmlPath);//"WebRoot/WEB-INF/struts-config.xml"
  		  Element root = doc.getRootElement();
    	  Element actionMappings=root.getChild("action-mapping");
    	 List<Element> list=actionMappings.getChildren();
    	 for(Element action:list){
    		 String actionName=action.getAttributeValue("name");
    	
     	
    		 String actionType=action.getAttributeValue("type");
    		 String actionPath=action.getAttributeValue("path");
    		 
    		 System.out.println("  actionMappings: actionName="+actionName+"; actionType="+actionType+"; actionPath="+actionPath);
    		 List<Element> forwardList=action.getChildren();
    		 Map<String,String> actionForwardMap=new HashMap<String,String>();
    		 for(Element forward:forwardList){
    			 String forwardName=forward.getAttributeValue("name");
    			 String forwardValue=forward.getAttributeValue("value");
    			 actionForwardMap.put(forwardName, forwardValue);
    			
    			 
    		 }
    		 String beanType="";
 			Element formbeans = root.getChild("formbeans");
 			List<Element> beanList = formbeans.getChildren();
 			for(Element bean:beanList){
 				if(actionName.equals(bean.getAttributeValue("name"))){
 					beanType = bean.getAttributeValue("type");
 					
 					break;
 				}
 			}
 			
    		 xmlBean.setFormBeanName(actionName);
 			xmlBean.setFormBeanType(beanType);
 			xmlBean.setActionName(actionName);
 			xmlBean.setActionType(actionType);
 			xmlBean.setActionPath(actionPath);
 			xmlBean.setActionForward(actionForwardMap);
 			
 			map.put(actionPath, xmlBean);
    		 
    		 
    	 }
    	  
    	  
    	  
    	  
    	  
    	  return map;
    	  
    	  
    	  
      }
      
      
      public static void main(String[] args){
  		try {
  			Map<String, XmlBean> map = read("WebRoot/WEB-INF/struts-config.xml");
  			
  			Set<String> keySet = map.keySet();
  			for(Iterator<String> it = keySet.iterator(); it.hasNext();){
  				String actionPath = it.next();
  				System.out.println(actionPath);
  				System.out.println(map.get(actionPath));
  			}
  		} catch (Exception e) {
  			e.printStackTrace();
  		}
  	}

  	
}
